package main

import (
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"context"
	"fmt"
	"time"
	"strconv"
	"go.mongodb.org/mongo-driver/bson"
)

type TimePoint struct {
	Begin int64 `bson:"begin"`
	End int64 `bson:"end"`
}

// 定义模拟的日志结构体
type LogRecord struct {
	Name string `bson:"name"`
	Content string `bson:"Content"`
	Time TimePoint `bson:"time"`
}

// 根据jobName过滤查找
type FindByJobName struct {
	FindByJobName string `bson:"name"`
}

type TimeBeforeCond struct {
	Before int64 `bson:$eq`
}

type DeleteCond struct {
	BeforeCond TimeBeforeCond `bson:"time.begin"`
}
func main() {
	ctx, _ := context.WithTimeout(context.Background(), 10 * time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://9.134.0.183:27017"))
	if err != nil {
		fmt.Println(err)
		return
	}

	collection := client.Database("my_db").Collection("task")

	// 清空表格记录
	collection.DeleteMany(context.TODO(), bson.M{})

	// 添加一批记录
	now := time.Now()
	for i := 0; i < 5; i++ {
		record := LogRecord{
			Name:"scanfile" + strconv.Itoa(i + 1),
			Content:"scan all work file" + strconv.Itoa(i + 1),
			Time:TimePoint{
				Begin:now.Unix() + int64(i * 60),
				End:now.Unix() + int64(i * 60 + 600),
			},
		}

		_, err := collection.InsertOne(context.TODO(), record)
		if err != nil {
			fmt.Println(err)
			return
		}
	}

	// 按照条件删除记录
	fmt.Println(now.Unix())

	delCond := 	&DeleteCond{
		BeforeCond:TimeBeforeCond{
			Before:now.Unix(),
		},
	}

	delResult, err := collection.DeleteMany(context.TODO(), delCond)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("delete ", delResult.DeletedCount)

	// 按条件查找一批记录
	op := options.FindOptions{}
	cursor, err := collection.Find(context.TODO(), bson.M{},
		op.SetLimit(2))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer cursor.Close(context.TODO())

	for cursor.Next(context.TODO()) {
		record := &LogRecord{}
		err = cursor.Decode(record)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(record)
	}
}
